﻿using System;
using System.Collections.Generic;
using ADLite;
using RiskMan.DataClass.AlfaDirectFolder;
using TheControllerRisk.Settings;

namespace RiskMan.DataClass
{
    public partial class Data
    {



        //Альфа директ
        public AlfaDirect AD = null;
        public TransactionAlfaDirect TransactionAlfaDirect = new TransactionAlfaDirect(RiskMan.MainWindow.StaticLevel);
        //string where = "";
        //string QueueTable = "";
        string OrderFieldsData = "ord_no, status, b_s, price, qty, rest, ts_time, place_code, p_code, acc_code, stop_price, blank, ord_type, acc_name, comments, type_desc, stop_price";
        string FinInfoFieldsData = "paper_no, last_price, sell, buy, p_code, place_code, max_deal, go_buy, min_deal,  high_bid, low_offer, close_price, decimals, price_step, prev_price, place_name, lot_size, board_code, board_name,  ANSI_name";
        string BalanceFieldsData = "acc_code, p_code, place_code, real_rest, plan_rest, real_vol, balance_price, bal_forword_vol, income_rest";
        //string PortfSectionBalField = "acc_code, section_code, treaty, forward_bal, money, daily_pl, rel_pl";
        //string SumBalanceField = "treaty, p_code, place_code, forword_rest";
        //string SumBalanceAccField = "acc_code, p_code, place_code, forword_rest";
        //string AccountsAlfaData = "treaty, full_name, i_last_update, start_margin, msg_margin, min_margin";
        //string BoardsAlfaData = "board_code, place_code, board_name, tax, price_type, i_last_update, place_name";

        string _resultMessage;

        /// <summary>
        /// Получение данных из таблиц
        /// </summary>
        public void SubscribeAlfaDirect()
        {
            //AD.GetLocalDBData("order_statuses", OrderStatusesFieldsData, "");
            //AD.GetLocalDBData("order_types", OrderStatusesFieldsData, "");
            AD.SubscribeTable("fin_info", FinInfoFieldsData, "", eSubsctibeOptions.Default, out _resultMessage);
            AD.SubscribeTable("orders", OrderFieldsData, "", eSubsctibeOptions.Default, out _resultMessage);
            AD.SubscribeTable("balance", BalanceFieldsData, "", eSubsctibeOptions.Default, out _resultMessage);
            //AD.SubscribeTable("order_statuses", OrderStatusesFieldsData, "", eSubsctibeOptions.Default, out ResultMessage);
            //AD.SubscribeTable("portf_section_bal", PortfSectionBalField, "", eSubsctibeOptions.Default, out ResultMessage);
            //AD.SubscribeTable("sum_balance", SumBalanceField, "", eSubsctibeOptions.Default, out ResultMessage);
            //AD.SubscribeTable("sum_balance_acc", SumBalanceAccField, "", eSubsctibeOptions.Default, out ResultMessage);
            //AD.SubscribeTable("accounts", AccountsAlfaData, "", eSubsctibeOptions.Default, out ResultMessage);
            //AD.SubscribeTable("boards", BoardsAlfaData, "", eSubsctibeOptions.Default, out ResultMessage);
        }

        #region OrderStatuses Alfa
        /// <summary>
        /// Получеине типов заявок
        /// </summary>
        /// <param name="tmpArray"></param>
        public void OrderStatusesItemsParsing(string[] tmpArray)
        {
            if (tmpArray.Length > 0)
                foreach (var item in tmpArray)
                {

                    string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    OrderStatuses orderStatuses = new OrderStatuses();
                    for (int i = 0; i < tmp.Length; i++)
                    {
                        if (i == 0)
                            orderStatuses.OrdStatus = tmp[i];
                        if (i == 1)
                            orderStatuses.Desctiption = tmp[i];
                    }

                    OrderStatusesItemsParsing(orderStatuses);
                }
        }

        /// <summary>
        /// Добавление или изменение данных в коллекции
        /// </summary>
        /// <param name="account"></param>
        public void OrderStatusesItemsParsing(OrderStatuses orderStatuses)
        {
            OrdersStatusesAlfa.Add(orderStatuses);
        }
        #endregion

        #region Accounts Alfa
        /// <summary>
        /// Создание и парсинг полученных строк для аккаунтов
        /// </summary>
        /// <param name="tmpArray"></param>
        public void AccountsItemsParsing(string[] tmpArray)
        {
            if (tmpArray.Length > 0)
                foreach (var item in tmpArray)
                {

                    string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    Accounts account = new Accounts();
                    for (int i = 0; i < tmp.Length; i++)
                    {
                        if (i == 0)
                            account.Treaty = Convert.ToInt32(tmp[i]);
                        if (i == 1)
                            account.FullName = tmp[i];
                        if (i == 2)
                            account.ILastUpdate = Convert.ToInt32(tmp[i]);
                        if (i == 3)
                            account.StrartMargin = Convert.ToDouble(tmp[i]);
                        if (i == 4)
                            account.MsgMargin = Convert.ToDouble(tmp[i]);
                        if (i == 5)
                            account.MinMargin = Convert.ToDouble(tmp[i]);
                    }

                    AccountItemsParsing(account);
                }
        }

        /// <summary>
        /// Добавление или изменение данных в коллекции
        /// </summary>
        /// <param name="account"></param>
        public void AccountItemsParsing(Accounts account)
        {
            AccountsAlfa.Add(account);
        }
        #endregion

        #region FinInfo Alfa
        /// <summary>
        /// Создание и парсинг полученных строк для финансовых инструментов
        /// </summary>
        /// <param name="tmpArray"></param>
        public void FinInfoItemsParsing(string[] tmpArray)
        {
            if (tmpArray.Length > 0)
                foreach (var item in tmpArray)
                {
                    string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    FinInfo finInfo = new FinInfo();
                    for (int i = 0; i < tmp.Length; i++)
                    {
                        if (i == 0)
                            finInfo.PaperNo = Convert.ToInt32(tmp[i]);
                        if (i == 1)
                            finInfo.LastPrice = Convert.ToDouble(tmp[i]);
                        if (i == 2)
                            finInfo.Sell = Convert.ToDouble(tmp[i]);
                        if (i == 3)
                            finInfo.Buy = Convert.ToDouble(tmp[i]);
                        if (i == 4)
                            finInfo.PCode = tmp[i];
                        if (i == 5)
                            finInfo.PlaceCode = tmp[i];
                        if (i == 6)
                            finInfo.MaxDeal = Convert.ToDouble(tmp[i]);
                        if (i == 7)
                            finInfo.GoBuy = Convert.ToDouble(tmp[i]);
                        if (i == 8)
                            finInfo.MinDeal = Convert.ToDouble(tmp[i]);
                        if (i == 9)
                            finInfo.HighBid = Convert.ToDouble(tmp[i]);
                        if (i == 10)
                            finInfo.LowOffer = Convert.ToDouble(tmp[i]);
                        if (i == 11)
                            finInfo.ClosePrice = Convert.ToDouble(tmp[i]);
                        if (i == 12)
                            finInfo.Decimals = Convert.ToInt32(tmp[i]);
                        if (i == 13)
                            finInfo.PriceStep = Convert.ToDouble(tmp[i]);
                        if (i == 14)
                            finInfo.PrevPrice = Convert.ToDouble(tmp[i]);
                        if (i == 15)
                            finInfo.PlaceName = tmp[i];
                        if (i == 16)
                            finInfo.LotSize = Convert.ToInt32(tmp[i]);
                        if (i == 17)
                            finInfo.BoardCode = tmp[i];
                        if (i == 18)
                            finInfo.BoardName = tmp[i];
                        if (i == 19)
                            finInfo.AnsiName = tmp[i];

                    }

                    FinInfoItemParsing(finInfo);
                }
        }

        /// <summary>
        /// Добавление или изменение данных в коллекции
        /// </summary>
        /// <param name="account"></param>
        public void FinInfoItemParsing(FinInfo tmpParam)
        {
            var tmpColl = FinInfoAlfa;
            bool result = true;
            if (tmpColl.Count > 0)
            {
                foreach (var item in tmpColl)
                {
                    if (item.PaperNo == tmpParam.PaperNo)
                    {
                        if (item.LastPrice != tmpParam.LastPrice && tmpParam.LastPrice != 0)
                            item.LastPrice = tmpParam.LastPrice;
                        if (item.PrevPrice != tmpParam.PrevPrice && tmpParam.PrevPrice != 0)
                            item.PrevPrice = tmpParam.PrevPrice;
                        result = false;
                    }
                }
            }

            if (result)
                tmpColl.Add(tmpParam);
        }
        #endregion

        #region Boards Alfa
        /// <summary>
        /// Создание и парсинг полученных строк для финансовых инструментов
        /// </summary>
        /// <param name="tmpArray"></param>
        public void BoardItemsParsing(string[] tmpArray)
        {
            if (tmpArray.Length > 0)
                foreach (var item in tmpArray)
                {

                    string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    Boards board = new Boards();
                    for (int i = 0; i < tmp.Length; i++)
                    {
                        if (i == 0)
                            board.BoardCode = tmp[i];
                        if (i == 1)
                            board.PlaceCode = tmp[i];
                        if (i == 2)
                            board.BoardName = tmp[i];
                        if (i == 3)
                            board.Tax = Convert.ToDouble(tmp[i]);
                        if (i == 4)
                            board.PriceType = tmp[i];
                        if (i == 5)
                            board.ILastUpdate = Convert.ToInt32(tmp[i]);
                        if (i == 6)
                            board.PlaceName = tmp[i];
                    }
                    BoardItemParsing(board);
                }
        }

        /// <summary>
        /// Добавление или изменение данных в коллекции Board
        /// </summary>
        /// <param name="account"></param>
        public void BoardItemParsing(Boards tmpParam)
        {
            var tmpColl = BoardsAlfa;
            bool result = true;
            if (tmpColl.Count > 0)
            {
                foreach (var item in tmpColl)
                {
                    if (item.BoardCode == tmpParam.BoardCode)
                    {
                        result = false;
                    }
                }
            }

            if (result)
                tmpColl.Add(tmpParam);
        }
        #endregion

        #region Balance Alfa
        /// <summary>
        /// Создание и парсинг полученных строк для табалицы Баланса
        /// </summary>
        /// <param name="tmpArray"></param>
        public void BalanceItemsParsing(string[] tmpArray)
        {
            if (tmpArray.Length > 0)
                foreach (var item in tmpArray)
                {
                    string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    Balance balance = new Balance();
                    for (int i = 0; i < tmp.Length; i++)
                    {
                        if (i == 0)
                            balance.AccCode = tmp[i];
                        if (i == 1)
                            balance.PCode = tmp[i];
                        if (i == 2)
                            balance.PlaceCode = tmp[i];
                        if (i == 3)
                            balance.RealRest = Convert.ToDouble(tmp[i]);
                        if (i == 4)
                            balance.PlanRest = Convert.ToDouble(tmp[i]);
                        if (i == 5)
                            balance.RealVol = Convert.ToDouble(tmp[i]);
                        if (i == 6)
                            balance.BalForwordVol = Convert.ToDouble(tmp[i]);
                        if (i == 7)
                            balance.IncomeRest = Convert.ToDouble(tmp[i]);
                    }

                    BalanceItemParsing(balance);
                }
        }

        /// <summary>
        /// Добавление или изменение данных в коллекции Balance
        /// </summary>
        /// <param name="account"></param>
        public void BalanceItemParsing(Balance tmpParam)
        {
            var tmpColl = BalanceAlfa;
            bool result = true;
            if (tmpColl.Count > 0)
            {
                foreach (var item in tmpColl)
                {
                    if (item.AccCode == tmpParam.AccCode && item.PCode == tmpParam.PCode && item.PlaceCode == tmpParam.PlaceCode)
                    {
                        if (item.RealRest != tmpParam.RealRest && tmpParam.RealRest != 0)
                            item.RealRest = tmpParam.RealRest;
                        if (item.PlanRest != tmpParam.PlanRest && tmpParam.PlanRest != 0)
                            item.PlanRest = tmpParam.PlanRest;
                        if (item.RealVol != tmpParam.RealVol && tmpParam.RealVol != 0)
                            item.RealVol = tmpParam.RealVol;
                        if (item.BalForwordVol != tmpParam.BalForwordVol && tmpParam.BalForwordVol != 0)
                            item.BalForwordVol = tmpParam.BalForwordVol;
                        result = false;
                    }
                }
            }

            if (result)
                tmpColl.Add(tmpParam);
        }
        #endregion

        #region Orders Alfa
        /// <summary>
        /// Создание и парсинг полученных строк для табалицы Orders
        /// </summary>
        /// <param name="tmpArray"></param>
        public void OrdersItemsParsing(string[] tmpArray)
        {
            if (tmpArray.Length > 0)
                foreach (var item in tmpArray)
                {
                    string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    Orders order = new Orders();
                    for (int i = 0; i < tmp.Length; i++)
                    {
                        if (i == 0)
                            order.OrdNo = Convert.ToInt64(tmp[i]);
                        if (i == 1)
                            order.Status = OrdersStatusesAlfaDirect(tmp[i]);
                        if (i == 2)
                            order.BS = tmp[i];
                        if (i == 3)
                            order.Price = Convert.ToDouble(tmp[i]);
                        if (i == 4)
                            order.Qty = Convert.ToInt32(tmp[i]);
                        if (i == 5)
                            order.Rest = Convert.ToInt32(tmp[i]);
                        if (i == 6)
                            order.TsTime = Convert.ToDateTime(tmp[i]);
                        if (i == 7)
                            order.PlaceCode = tmp[i];
                        if (i == 8)
                            order.PCode = tmp[i];
                        if (i == 9)
                            order.AccCode = tmp[i];

                        if (i == 10)
                            order.StopPrice = Convert.ToDouble(tmp[i]);
                        if (i == 11)
                            order.Blank = tmp[i];
                        if (i == 12)
                            order.OrdType = tmp[i];
                        if (i == 13)
                            order.AccName = tmp[i];
                        if (i == 14)
                            order.Comments = tmp[i];
                    }

                    OrderItemParsing(order);
                }
        }

        /// <summary>
        /// Добавление или изменение данных в коллекции Orders
        /// </summary>
        /// <param name="account"></param>
        public void OrderItemParsing(Orders tmpParam)
        {
            var tmpColl = OrdersAlfa;
            bool result = true;
            if (tmpColl.Count > 0)
            {
                foreach (var item in tmpColl)
                {
                    if (item.OrdNo == tmpParam.OrdNo)
                    {
                        if (item.Status != tmpParam.Status && !String.IsNullOrEmpty(tmpParam.Status))
                            item.Status = tmpParam.Status;
                        if (item.Rest != tmpParam.Rest && tmpParam.Rest != 0)
                            item.Rest = tmpParam.Rest;

                        result = false;
                    }
                }
            }

            if (result)
                tmpColl.Add(tmpParam);
        }
        #endregion

        //Событие изменения таблицы
        public void AD_OnTableChanged(string TableName, string tableParams, object data, object fieldTypes)
        {

            string[] tmpArray = (Convert.ToString(data)).Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (TableName == "accounts")
                AccountsItemsParsing(tmpArray);
            if (TableName == "fin_info")
                FinInfoItemsParsing(tmpArray);
            if (TableName == "boards")
                FinInfoItemsParsing(tmpArray);
            if (TableName == "balance")
                BalanceItemsParsing(tmpArray);
            if (TableName == "orders")
                OrdersItemsParsing(tmpArray);
            //if (TableName == "order_statuses")
            //    OrderStatusesItemsParsing(tmpArray);

        }

        public string OrdersStatusesAlfaDirect(string status)
        {
            string result = cfg.Unknown;

            if (status == "M")
                result = cfg.Performed;
            if (status == "O" || status == "Z")
                result = cfg.Active;
            if (status == "W")
                result = cfg.Cancel;

            return result;

        }


        /// <summary>
        /// Получаем данные по комментарию и номеру заявки в режиме работы альфы директ. 
        /// </summary>
        /// <param name="tmpArray"></param>
        /// <returns></returns>
        public Orders GetLocalDBDataOrdersAlfa(string tmpArray)
        {
            Orders order = new Orders();
            string[] tmp = tmpArray.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < tmp.Length; i++)
            {
                if (i == 0)
                    order.OrdNo = Convert.ToInt64(tmp[i]);
                if (i == 1)
                    order.Status = OrdersStatusesAlfaDirect(tmp[i]);
                if (i == 2)
                    order.BS = tmp[i];
                if (i == 3)
                    order.Price = Convert.ToDouble(tmp[i]);
                if (i == 4)
                    order.Qty = Convert.ToInt32(tmp[i]);
                if (i == 5)
                    order.Rest = Convert.ToInt32(tmp[i]);
                if (i == 6)
                    order.TsTime = Convert.ToDateTime(tmp[i]);
                if (i == 7)
                    order.PlaceCode = tmp[i];
                if (i == 8)
                    order.PCode = tmp[i];
                if (i == 9)
                    order.AccCode = tmp[i];

                if (i == 10)
                    order.StopPrice = Convert.ToDouble(tmp[i]);
                if (i == 11)
                    order.Blank = tmp[i];
                if (i == 12)
                    order.OrdType = tmp[i];
                if (i == 13)
                    order.AccName = tmp[i];
                if (i == 14)
                    order.Comments = tmp[i];
                if (i == 15)
                    order.TypeDesc = tmp[i];
                if (i == 16)
                {
                    double tmpStopPrice;
                    Double.TryParse(tmp[i], out tmpStopPrice);
                    order.StopPrice = tmpStopPrice;
                }

            }
            return order;
        }

        /// <summary>
        /// Получаем данные списка заявок по комментарию и номеру заявки в режиме работы альфы директ. 
        /// </summary>
        /// <param name="tmpArray"></param>
        /// <returns></returns>
        public List<Orders> GetLocalDBDataOrdersAlfaArray(string tmpArray)
        {
            List<Orders> list = new List<Orders>();
            string[] tmpArrayString = tmpArray.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in tmpArrayString)
            {
                Orders order = new Orders();
                string[] tmp = item.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < tmp.Length; i++)
                {
                    if (i == 0)
                        order.OrdNo = Convert.ToInt64(tmp[i]);
                    if (i == 1)
                        order.Status = OrdersStatusesAlfaDirect(tmp[i]);
                    if (i == 2)
                        order.BS = tmp[i];
                    if (i == 3)
                        order.Price = Convert.ToDouble(tmp[i]);
                    if (i == 4)
                        order.Qty = Convert.ToInt32(tmp[i]);
                    if (i == 5)
                        order.Rest = Convert.ToInt32(tmp[i]);
                    if (i == 6)
                        order.TsTime = Convert.ToDateTime(tmp[i]);
                    if (i == 7)
                        order.PlaceCode = tmp[i];
                    if (i == 8)
                        order.PCode = tmp[i];
                    if (i == 9)
                        order.AccCode = tmp[i];

                    if (i == 10)
                        order.StopPrice = Convert.ToDouble(tmp[i]);
                    if (i == 11)
                        order.Blank = tmp[i];
                    if (i == 12)
                        order.OrdType = tmp[i];
                    if (i == 13)
                        order.AccName = tmp[i];
                    if (i == 14)
                        order.Comments = tmp[i];
                    if (i == 15)
                        order.TypeDesc = tmp[i];
                    if (i == 16)
                        order.StopPrice = Convert.ToDouble(tmp[i]);

                }
                list.Add(order);
            }
            return list;
        }
    }
}
